import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:schoollifedemo/business/login/login_page.dart';
import 'package:schoollifedemo/business/welcome/welcome_page.dart';

import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/entity/Entity.dart';
import 'package:schoollifedemo/main_viewmodel.dart';

void main() {
  runApp(const MyApp());
  SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
      statusBarColor: Colors.white, statusBarIconBrightness: Brightness.dark);
  SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}

class MyApp extends BaseStatefulPage {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends BasePageState<MyApp> {
  final MainViewModel _mainViewModel = MainViewModel();

  @override
  void initState() {
    _mainViewModel.init();

    _getAppIsFirstStart().asStream().listen((isFirstStart) {
      if (isFirstStart == true) {
        _mainViewModel.loadingSubject.add(CommonLoadingState.successTypeOne);
      } else if (isFirstStart == false) {
        _mainViewModel.loadingSubject.add(CommonLoadingState.successTypeTwo);
      } else {
        _mainViewModel.loadingSubject.add(CommonLoadingState.failure);
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _mainViewModel.dispose();
    super.dispose();
  }

  Future<bool?> _getAppIsFirstStart() async {
    String? saveVersion = await _mainViewModel.getAppVersion();
    if (_mainViewModel.getApplication().getAppVersion() == saveVersion) {
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: StreamBuilder(
        initialData: CommonLoadingState.loading,
        stream: _mainViewModel.loadingSubject,
        builder: (buildContext, spot) {
          CommonLoadingState? commonLoadingState =
              spot.data as CommonLoadingState?;
          switch (commonLoadingState) {
            case CommonLoadingState.loading:
              return const LoadingWidget();
            case CommonLoadingState.successTypeOne:
              return const WelcomePage();
            case CommonLoadingState.successTypeTwo:
              return const LoginPage();
            case CommonLoadingState.failure:
              return const CommonErrorWidget('出错了，对不起');
            default:
              return Container();
          }
        },
      ),
    );
  }
}
